package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Array;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private WorkspaceService workspaceService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list  = new ArrayList<>();
        list.add(begin);
        while(!end.equals(begin))
        {
            //日期计算，从begin算到end
            begin=begin.plusDays(1);
            list.add(begin);

        }
        String join = StringUtils.join(list, ",");
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(join);

        ArrayList<Double> list2 = new ArrayList<>();
        for (LocalDate localDate : list) {
            /*
                这个用法用来获取某一天的00:00和59:99时间
             */
            LocalDateTime begintime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Double sum=orderMapper.sumByTime(begintime,endtime);
            sum=sum==null?0.0:sum;
            list2.add(sum);
        }
        String join2 = StringUtils.join(list2, ",");
        turnoverReportVO.setTurnoverList(join2);
        return turnoverReportVO;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //将所有日期加入数组用于后续遍历显示每天的情况
        ArrayList<LocalDate> list  = new ArrayList<>();
        list.add(begin);
        while (!end.equals(begin))
        {
            begin=begin.plusDays(1);
            list.add(begin);
        }
        UserReportVO userReportVO = new UserReportVO();
        String date = StringUtils.join(list, ",");
        userReportVO.setDateList(date);

        //每天的新增用户总数
        ArrayList<Integer> list2 = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime begintime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer count=userMapper.countByTime(begintime,endtime);
            count=count==null?0:count;
            list2.add(count);
        }
        String newCount = StringUtils.join(list2, ",");
        userReportVO.setNewUserList(newCount);

        //每天的用户总数
        ArrayList<Integer> list3 = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer count=userMapper.count(endtime);
            count=count==null?0:count;
            list3.add(count);
        }
        String count = StringUtils.join(list3, ",");
        userReportVO.setTotalUserList(count);
        return userReportVO;
    }

    @Override
    public OrderReportVO getordersStatistics(LocalDate begin, LocalDate end) {
        //遍历首尾日期拿到日期数组
        OrderReportVO orderReportVO = new OrderReportVO();
        ArrayList<LocalDate> list= new ArrayList<>();
        list.add(begin);
        while (!end.equals(begin))
        {
            begin=begin.plusDays(1);
            list.add(begin);
        }
        String date = StringUtils.join(list, ",");
        orderReportVO.setDateList(date);

        //遍历日期数组，查询每天订单总数和有效订单总数,并放入订单列表中
        ArrayList<Long> list1= new ArrayList<>();
        ArrayList<Long> list2 = new ArrayList<>();
        for (LocalDate localDate : list) {
            LocalDateTime begintime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Long sum2 = orderMapper.sumeveryday(begintime, endtime, 5);
            Long sum=orderMapper.sumeveryday(begintime,endtime,null);
            list1.add(sum);
            list2.add(sum2);
        }
        String sumeveryday = StringUtils.join(list1, ",");
        String sum2everyday = StringUtils.join(list2, ",");
        orderReportVO.setOrderCountList(sumeveryday);
        orderReportVO.setValidOrderCountList(sum2everyday);

        //查询给的日期内总订单数和总有效订单数    ·
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);
        Integer count=orderMapper.count(endtime,null);
        Integer ValidCount=orderMapper.count(endtime,5);
        orderReportVO.setTotalOrderCount(count);
        orderReportVO.setValidOrderCount(ValidCount);

        Double orderCompletionRate=0.0;
        if(count!=0)
            orderCompletionRate=ValidCount.doubleValue()/count;
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime begintime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.top10(begintime, endtime);

        List<String> name = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String namelist = StringUtils.join(name, ",");

        List<Integer> number = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberlist = StringUtils.join(number, ",");
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNumberList(numberlist);
        salesTop10ReportVO.setNameList(namelist);
        return salesTop10ReportVO;
    }

    @Override
    public void export(HttpServletResponse response) throws IOException {
        /*
            1.查询数据库，获得营业数据
         */
        //往前三十天
        LocalDate datebegin = LocalDate.now().minusDays(30);
        //往前一天 昨天
        LocalDate dateend = LocalDate.now().minusDays(1);

        LocalDateTime begin = LocalDateTime.of(datebegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateend, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);

        /*
            2.通过POI将数据写入excel文件
         */
        //新建一个和模版文件一模一样的文件-----因为resource是静态文件，无法直接修改而是新建一个一模一样的文件，所以和read读取内容时候不一样
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        XSSFWorkbook excel = new XSSFWorkbook(in);

        //填充数据
        XSSFSheet sheet1 = excel.getSheet("Sheet1");

        XSSFRow row = sheet1.getRow(1);
        row.getCell(1).setCellValue("时间： "+datebegin+"至"+dateend);

        XSSFRow row1 = sheet1.getRow(3);
        row1.getCell(2).setCellValue(businessData.getTurnover());

        row1.getCell(4).setCellValue(businessData.getOrderCompletionRate());

        row1.getCell(6).setCellValue(businessData.getNewUsers());

        XSSFRow row2 = sheet1.getRow(4);
        row2.getCell(2).setCellValue(businessData.getValidOrderCount());

        row2.getCell(4).setCellValue(businessData.getUnitPrice());

        //明细数据内容
        for (int i = 0; i <30 ; i++) {
            LocalDate date = datebegin.plusDays(i);
            //查询某一天的营业数据
            BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            //获得某一行
            XSSFRow row3 = sheet1.getRow(7 + i);
            row3.getCell(1).setCellValue(date.toString());
            row3.getCell(2).setCellValue(businessData1.getTurnover());
            row3.getCell(3).setCellValue(businessData1.getValidOrderCount());
            row3.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            row3.getCell(5).setCellValue(businessData1.getUnitPrice());
            row3.getCell(6).setCellValue(businessData1.getNewUsers());
        }


        /*
            3.通过输出流将excel文件下载到客户端浏览器
         */
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);


        excel.close();
        outputStream.close();
    }
}
